//
//  MXUtility.m
//  MoXiProject
//
//  Created by 周筱雯 on 2017/5/27.
//  Copyright © 2017年 周筱雯. All rights reserved.
//

#import "MXUtility.h"

/**
 获取IP地址需要导入
 */
#import <ifaddrs.h>
#import <arpa/inet.h>

#import <CommonCrypto/CommonDigest.h> //md5需导入文件

@implementation MXUtility


/**
 *提示框,Tim添加
 */
+ (void)showTips:(NSString *)tips
{
    if (!tips)return;
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode=MBProgressHUDModeText;
    hud.detailsLabelText=tips;
    hud.detailsLabelFont = [UIFont systemFontOfSize:15];
    hud.removeFromSuperViewOnHide=YES;
    hud.minSize=CGSizeMake(140, 25);
    [hud show:YES];
    [hud hide:YES afterDelay:1.2];
}


+ (void)setExtraCellLineHidde:(UITableView *)tableView tabHeader:(BOOL) header tabFooter:(BOOL) footer
{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    if (!header) {
        [tableView setTableHeaderView:view];
    }
    if (!footer) {
        [tableView setTableFooterView:view];
    }
}

//MD5加密
+(NSString *) md5: (NSString *) inPutText
{
    if (!inPutText) {
        return inPutText;
    }
    const char *cStr = [inPutText UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    NSString *md5Result = [NSString stringWithFormat:
                           @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           result[0], result[1], result[2], result[3],
                           result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11],
                           result[12], result[13], result[14], result[15]
                           ];
    return md5Result;
}
//判断非空
+(NSString *)NSNULLString:(NSString *)string{
    if( [string isEqualToString:@""]||[string length]==0||[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){
        return string;
    }
    return nil;
}

//限制特殊字符不能输入@
+(int) XZInputText:(NSString *) stringText{
    NSCharacterSet *nameCharacters = [NSCharacterSet
                                      characterSetWithCharactersInString:@"`~!@#$%^&*()+=|{}':;',\\[\\].<>?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？"];
    NSRange userNameRange = [stringText rangeOfCharacterFromSet:nameCharacters];
    
    if (userNameRange.location != NSNotFound) {
        return 0;//包含特殊字符
    }else{
        return 1;
    }
    return 1;
    
    //用法
    
    /**
     if ([self XZInputText:_userAddress.text]==0) {
     MessageSHAREShow(@"不能输入特殊字符");
     return false;
     }
     */
}
//判断密码
+(BOOL)CheckInput:(NSString *)_text{
    NSString *Regex = @"\\w{6,16}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [emailTest evaluateWithObject:_text];
}

//检测手机号
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    if(mobileNum.length == 0 || mobileNum == nil || mobileNum.length < 11) return NO;
    
    NSString *Regex = @"^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|147)\\d{8}$";//以前用的
    NSPredicate *phone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [phone evaluateWithObject:mobileNum];
}
//获取IP地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}


//!!!!: 风火轮加载信息
/**
 *  风火轮加载信息
 *
 *  @param _targetView 对象
 *  @param _msg        提示信息
 */
+ (void)showMBProgress:(UIView *)_targetView message:(NSString *)_msg {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:_targetView];
        progressHUD.mode = MBProgressHUDModeIndeterminate;
        [progressHUD show:YES];
        progressHUD.labelText = _msg;
        [_targetView addSubview:progressHUD];
    });
    
}

+ (void)hideMBProgress:(UIView*)_targetView{
    
    [MBProgressHUD hideHUDForView:_targetView animated:YES];
}

/**
 *  将时间戳转换为指定格式时时间
 *
 *  @param strTimestamp  传入的时间戳
 *  @param strDateFormat 时间的格式
 *
 *  @return 返回的时间
 */
+ (NSString *)getTimeWithTimestamp:(NSString *)strTimestamp WithDateFormat:(NSString *)strDateFormat
{
    
    /**
     
     时间戳转换
     
     */
//    if ([strTimestamp isEqualToString:@"0"]||[strTimestamp length]==0)
//    {
//        return @"";
//    }
//    
//    long long time;
//    if (strTimestamp.length == 10) {
//        time = [strTimestamp longLongValue];
//    }
//    else if (strTimestamp.length == 13){
//        time = [strTimestamp longLongValue]/1000;
//    }
//    
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
//    
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:strDateFormat];
//    NSString *strTime = [formatter stringFromDate:date];
//    return strTime;
    
    
    
    /**
     
     - returns:  时间转换yyyy-MM-dd
     
     重点 服务器返回的是一个yyyy-MM-dd HH:mm:ss格式  需要先获取一个格式一样的本地时间,才可以进行正常转换
     
     */
    
    
        NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
        NSString *dateString=[NSString stringWithFormat:@"%@", strTimestamp];
    
        NSDate *date =[dateFormat dateFromString:dateString];
    
        NSDateFormatter* dateFormat2 = [[NSDateFormatter alloc] init];
    
        [dateFormat2 setDateFormat:strDateFormat];
    
        NSString *publishtimeStr = [dateFormat2 stringFromDate:date ];
    
        return  publishtimeStr;
}
+ (NSAttributedString *)getAmountWithColor:(UIColor *)textColor
                                 amoutFont:(UIFont *) anFont
                                  unitFont:(UIFont *) unFont
                                    amount:(NSString *)amount
                                      unit:(NSString *)unit{
    if (amount == nil) {
        amount = @"";
    }
    if (unit == nil) {
        unit = @"";
    }
    NSString *str = [NSString stringWithFormat:@"%@%@",amount,unit];
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    [attrStr addAttribute:NSFontAttributeName
                    value:anFont
                    range:NSMakeRange(0, amount.length)];
    
    [attrStr addAttribute:NSFontAttributeName
                    value:unFont
                    range:NSMakeRange(amount.length, unit.length)];
    
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:textColor
                    range:NSMakeRange(0, str.length)];
    
    
    return [[NSAttributedString alloc] initWithAttributedString:attrStr];
}


// 判断身份证是否正确
+(BOOL)judgeIdentityCardNo:(NSString*)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
    
    
}

+(void)topLayerborder:(UIView *)view borderColor:(UIColor *) color{
    //绘制view上边框
    CALayer *bod = [CALayer layer];
    bod.backgroundColor = color.CGColor;//CGRectGetMinX(view.frame)
    bod.frame = CGRectMake(0, 0, view.width, 0.5);
    [view.layer addSublayer:bod];
}

+(void)bottomLayerborder:(UIView *)view borderColor:(UIColor *) color{
    CALayer *bottomLayer = [CALayer layer];
    bottomLayer.backgroundColor = color.CGColor;
    bottomLayer.frame = CGRectMake(0, view.height - 1, view.width, 1);
    [view.layer addSublayer:bottomLayer];
}

+(void)leftLayerborder:(UIView *)view borderColor:(UIColor *) color{
    CALayer *bottomLayer = [CALayer layer];
    bottomLayer.backgroundColor = color.CGColor;
    bottomLayer.frame = CGRectMake(0.5, 0, 0.5, view.height);
    [view.layer addSublayer:bottomLayer];
    
}

+(void)rightLayerborder:(UIView *)view borderColor:(UIColor *) color{
    CALayer *bottomLayer = [CALayer layer];
    bottomLayer.backgroundColor = color.CGColor;
    bottomLayer.frame = CGRectMake(view.width - 0.5, 0, 0.5, view.height);
    [view.layer addSublayer:bottomLayer];
    
}



@end
